package jack.code.hnzb.task;

import com.google.gson.reflect.TypeToken;
import jack.code.hnzb.rule.SearchRule;
import jack.code.hnzb.service.SendMessage;
import jack.code.hnzb.utils.GsonUtil;
import jack.code.hnzb.utils.RedisUtil;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.util.StringUtils;

import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.Map;

/**
 * 湖南招标监管网task
 * Created by LiJiakui on 17/8/30.
 */
//@Component
public class BiddingTaskBack {
    private static final Logger logger = Logger.getLogger(BiddingTaskBack.class);
    //当前查询到的记录数
    private static final String REDIS_KEY = "hnzbjb-recordNum";
//    private static final String REDIS_LIST_KEY = "hnzbjb-list";
    private static final String WEB_URL = "http://www.bidding.hunan.gov.cn/jyxxzb/";


//    @Scheduled(cron = "0 0/5 * * * ?")
//    @Scheduled(cron = "0/1 * * * * ?")
    public void hnzbWatcher(){
        logger.info("----开始爬取数据-----");
        //是否结束当前查询任务
        boolean shutDown = false;
        int sendTime = 0;//发送次数
        //查询最后一次任务的ID
        String recordNum = RedisUtil.getJedisVal(REDIS_KEY);
        if(StringUtils.isEmpty(recordNum)){
            recordNum = "1087";
        }
        Integer num = Integer.parseInt(recordNum);
        try {
            while (shutDown==false){
                //如果当前任务已经发送了20次,那么就跳出任务,等待下一次
                if(sendTime==20){
                    shutDown = true;
                    logger.info("已经超过了单次发送次数,2分钟后继续执行");
                    continue;

                }
                //需要查询的数据页数
                num = num+1;
                String url=WEB_URL+num+".jhtml";
                //线程休眠2秒,防止被限制
                Thread.sleep(2000);
                Document doc = Jsoup.connect(url).timeout(60000).get();

                //伪装浏览器
//              Jsoup.connect(url).userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31");

                Element lbProclaimTitleEle = doc.getElementById("lbProclaimTitle");
                Element lbReleasetTimeEle = doc.getElementById("lbReleasetTime");

                String lbProclaimTitle = lbProclaimTitleEle==null?"":lbProclaimTitleEle.text();
                String lbReleaseTime = lbReleasetTimeEle==null?"":lbReleasetTimeEle.text();
                if(StringUtils.isEmpty(lbProclaimTitle)){
                    boolean ls = true;
                    for(int i=1;i<=10;i++){
//                        logger.info("继续查询10次,当前第:"+i+"次");
                        System.out.println(WEB_URL+(num+i)+".jhtml");
                        String s = Jsoup.connect(WEB_URL+(num+i)+".jhtml").timeout(60000).get().getElementById("lbProclaimTitle").text();
                        if(StringUtils.isEmpty(s)==false){
                            ls = false;
                            num = num+i-1;
                            break;
                        }
                    }
                    shutDown = ls;
                    continue;
                }else{
                    StringBuffer sb = new StringBuffer();
                    sb.append(lbProclaimTitle);
                    sb.append(lbReleaseTime);
                    logger.info("\nresult---------"+sb.toString());
                    if(!"title".equals(SearchRule.range())){
                        Element table = doc.getElementById("lbProclaimContent");
                        sb.append(table.text());
                    }
                    //所有返回数据
                    String msg = sb.toString();

                    //检索中环相关
                    String rule = SearchRule.searchBidding(msg);
                    if(!"".equals(rule)){
                        sendTime++;
                        HttpResponse response = SendMessage.sendMsg1("信息来源:湖南招标监管网\n"+"命中索引:"+rule+"\n"+lbProclaimTitle + " \n" + lbReleaseTime + " \n" + "查询地址:" + url);//钉钉机器人起飞
                        if(response == null){
                            return ;
                        }else{
                            if (response.getStatusLine().getStatusCode()== HttpStatus.SC_OK){
                                String result= EntityUtils.toString(response.getEntity());
//                                logger.info("dingding--"+result);
                                Map<String,String> resultMap = GsonUtil.fromJson(result,new TypeToken<HashMap<String,String>>(){}.getType());
                                if(!"0".equals(resultMap.get("errcode"))){
//                                    logger.info("这条数据可能发送失败了,查询地址:"+url);
                                    SendMessage.sendMsg1("这条数据可能发送失败了,查询地址:"+url);
                                }
                            }
                        }
                    }
                    //记录当前查询数据到redis
//                    RedisUtil.lpush(REDIS_LIST_KEY,sb.toString());
                    RedisUtil.setJedisVal(REDIS_KEY,num.toString());
                }
            }
        } catch (SocketTimeoutException e) {
            e.printStackTrace();
//            SendMessage.sendMsg1("SOS SOS SOS,服务器出现严重的问题,随时可能爆炸,快去找哥哥帮忙!\n异常信息:"+e.getMessage());
            return ;
        } catch (Exception e) {
            e.printStackTrace();
//            SendMessage.sendMsg1("SOS SOS SOS,服务器出现严重的问题,随时可能爆炸,快去找哥哥帮忙!\n异常信息:"+e.getMessage());
            return ;
        }finally {
            logger.info("本次检索结束");
        }

    }
//    @Scheduled(cron = "0 0 6 * * ?")
//    public void sayMorning(){
//        SendMessage.sendMsg1("一天之计在于晨,各位老大,小弟已经忙了一夜了,没有偷懒哦!");
//    }
//
//    @Scheduled(cron = "0 0 23 * * ?")
//    public void sayNight(){
//        SendMessage.sendMsg1("已经很晚了,老大您快睡觉吧,我自己可以的!");
//    }
}
